package com.ldu.houserent.controller.backend;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ldu.houserent.common.base.BaseController;
import com.ldu.houserent.common.dto.JsonResult;
import com.ldu.houserent.common.util.PageUtil;
import com.ldu.houserent.entity.Feedback;
import com.ldu.houserent.service.FeedbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * 后台 用户反馈管理 控制器
 */
@Controller("backFeedbackController")
public class FeedbackController extends BaseController {

    @Autowired
    private FeedbackService feedbackService;

    /*
        进入用户反馈列表页面
     */
    @RequestMapping("/admin/feedback")
    public String feedback(@RequestParam(value = "page", defaultValue = "1") Long pageNumber, @RequestParam(value = "size", defaultValue = "6") Long pageSize, Model model) {
        //封装page
        Page page = PageUtil.initMpPage(pageNumber, pageSize);
        //进行查询
        Feedback condition = new Feedback();
        //如果不是管理员，则只查询自身的反馈
        if (!loginUserIsAdmin()){
            condition.setUserId(getLoginUserId());
        }
        Page<Feedback> feedbackPage = feedbackService.findAll(page, condition);
        model.addAttribute("pageInfo", feedbackPage);
        model.addAttribute("pagePrefix", "/admin/feedback?");
        model.addAttribute("tab", "feedback-list");         //鼠标点击后，改变页面中的字体颜色样式
        model.addAttribute("isAdmin",loginUserIsAdmin());       //传入feedback-list.jsp页面，给c:if做判断条件用
        return "admin/feedback-list";
    }

    /*
        回复反馈
     */
    @RequestMapping(value = "/admin/feedback/reply/submit",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult replySubmit(Feedback feedback){       //传过来feedback对象
        feedbackService.update(feedback);
        return JsonResult.success("回复成功");
    }

    /*
        删除反馈
     */
    @RequestMapping("/admin/feedback/delete")
    @ResponseBody
    public JsonResult deleteFeedback(@RequestParam("id")Long id){
        try {
            Feedback feedback = feedbackService.get(id);   //根据id获取到新闻资讯
            if (feedback==null){
                return JsonResult.error("操作失败，用户反馈不存在");
            }
            if(!loginUserIsAdmin() && !Objects.equals(feedback.getUserId(),getLoginUserId())){      //如果不是管理员并且当前用户不是反馈意见的用户
                return JsonResult.error("这不是您的反馈，您没有权限删除该条反馈");
            }
            feedbackService.delete(id);     //删除用户反馈
        }catch (Exception e){
            return JsonResult.error("删除用户反馈失败");
        }
        return JsonResult.success("删除用户反馈成功");
    }

}
